<?php
  class set_static_variable {
    public static $nid = 0;

    public function get_nid() {
      return self::$nid;
    }

    public function set_nid($val) {
      self::$nid = $val;
    }
  }

	function load_validation($nid) {
		$stat = new set_static_variable();
			if ($stat->get_nid() == 0) {
				$stat->set_nid($nid);
			}
	}



function find_empty($fieldname, $value, $label) {
  if ($value == "") {
    form_set_error($fieldname, $label . ' field should not be empty');
  }
}

/*District Validation*/
function distvalidation($dist_value,$title){

//print_r($title);

if(array_key_exists('0', $dist_value) && count($dist_value)==1){
   		//echo "you choose all - Correct";
  }

 if(count($dist_value)>1 && $dist_value['0']=='0'){
			//echo "if you choose all you cannot choose other district";
			form_set_error($dist_value, t('%title If you choose all you cannot choose other district', array('%title' => $title)));

	}


     return 0;
	}


function url_validation($url) {

  $trans = 'http://';
  $secure_trans = 'https://';
  //echo "ff".$test = '';

  if ($url == $trans  || $url == $test  || empty($url) == ''  || $url == $secure_trans) {
	//echo "-1";
  }
  if (!startsWith($url, $secure_trans) && !startsWith($url, $trans)) {
   //echo "0";
   form_set_error('URL', t('%title Please Give Valid URL
   ', array('%title' => $title)));
     return 0;
  }

   //echo "2";
  //form_set_error('URL', t('%title right', array('%title' => $title)));
 // return 0;

}


function startsWith($string, $char) {
    $length = strlen($char);
    return (substr($string, 0, $length) === $char);
}

function endsWith($string, $char) {
    $length = strlen($char);
    $start =  $length *-1; //negative
    return (substr($string, $start, $length) === $char);
}


function date_validation($valid_date) {
  $today = date("d/m/Y");

  return dateDiff('/', $valid_date, $today);
}

function dateDiff($dformat, $endDate, $beginDate) {

	 $date_parts1=explode($dformat, $beginDate);
	 $date_parts2=explode($dformat, $endDate);

	if ( !function_exists('gregoriantojd') ) {

		$start_date=greg_alter($date_parts1[1], $date_parts1[0], $date_parts1[2]);
	}
	else{
	  $start_date=gregoriantojd($date_parts1[1], $date_parts1[0], $date_parts1[2]);
	}
	if ( !function_exists('gregoriantojd') ) {

	  $end_date=greg_alter($date_parts2[1], $date_parts2[0], $date_parts2[2]);
	}
	else{
		$end_date=gregoriantojd($date_parts2[1], $date_parts2[0], $date_parts2[2]);
	}
	return $end_date - $start_date;
}

//Bad characters validation

function chkbadchar ($str, $title, $field_name){
	//$str = htmlspecialchars($str);
	//echo "123".$str;
	$str_title = strtoupper($str);
	$str_title = strip_tags($str_title);
	$str_title = htmlspecialchars($str_title);
	//$badch=array();
  	//$badch = array('SELECT','INSERT','DELETE','DROP','--','<','>','#', '*', '^',);
$badch = array('SELECT','INSERT','DELETE', 'UPDATE', 'DROP','ALTER','CHANGE','MODIFY','--','<','>','#', '*', '^','~','`','!','@','$','%','&','+','=','|',':',';','?','{','}','\'','--','"');


  if (!(is_null($str_title)) || trim($str_title)!="") {
    for ($i=0;$i<count($badch);$i++) {
      if (strpos($str_title,$badch[$i]) !== false) {
	 //echo "123".$title;
	   form_set_error($field_name, t('%title field contains bad characters', array('%title' => $title)));
        //return 0;
      }
    }
  }

} //function chkbadchar()

function chkbadpass ($str, $title, $field_name){
	$str = htmlspecialchars($str);
	$str_title = strtoupper($str);
	$str_title = strip_tags($str_title);
	//$badch=array();
  	//$badch = array('SELECT','INSERT','DELETE','DROP','--','<','>','#', '*', '^',);
$badch = array('SELECT','INSERT','DELETE','DROP','ALTER','CHANGE','MODIFY','--','<','>','#','$','&',':',';','\'','"');


  if (!(is_null($str_title)) || trim($str_title)!="") {
    for ($i=0;$i<count($badch);$i++) {

      if (strpos($str_title,$badch[$i]) > -1) {
	   form_set_error($field_name, t('%title field contains bad characters', array('%title' => $title)));
        return 0;
      }
    }
  }

} //function chkbadchar()


function badurl($str, $title, $field_name){
	$str_title = strtoupper($str);

	//$badch=array();

	$badch = array('SELECT','INSERT','DELETE','DROP','ALTER','CHANGE','MODIFY');


  if (!(is_null($str_title)) || trim($str_title)!="") {
    for ($i=0;$i<count($badch);$i++) {

      if (strpos($str_title,$badch[$i]) > -1) {
	   form_set_error($field_name, t('%title field contains bad characters', array('%title' => $title)));
        return 0;
      }
    }
  }

} //function badurl()

// Maximum string length validation

function maxlength_validation($str, $max_length, $title, $field_name) {

  if (strlen($str) > $max_length)
    form_set_error($field_name, $title . ' field value may not be longer than ' . $max_length . ' characters.');

} //function maxlength_validation()


// Minimum string length validation

function minilength_validation($str, $min_length, $title,$field_name) {
	if(strlen($str) != 0 ){

  		if (strlen($str) < $min_length)
    	form_set_error($field_name, $title . ' field must have at least ' . $min_length . ' characters.');
	}
} //function minilength_validation()


// URL validation

function isURL($url = NULL) {

  if($url==NULL) return false;

  $badch = array('select','INSERT','DELETE','DROP','ALTER','CHANGE','MODIFY');
  //$regex = '/(http|https):\/\/[A-Za-z0-9\.-]{2,}\.[A-Za-z]{2}/'; // followed by a TLD
	if (preg_match('|^http(s)?://[a-z]+(.[a-z]+)*(:+)?(/.*)?$|i', $url) ){
	 		foreach($badch as $key=>$val) {
			if (preg_match("/\b$val\b/i", $url)) {
			return 0;
			}
			//else {return 1;}
		}
	  return 1;
	 } else { return 0;}


} //function isURL()


//Telephone number validation

function telephone_validation ($str, $title) {

  $goodchar = " 1234567890.-+";

  for ($i=0;$i<strlen($str);$i++) {
    if (strpos($goodchar,$str{$i}) == false) {
      form_set_error('title_length', $title . ' field doesn\'t contain valid telephone number.');
      return 0;
    }
  }

} //function telephone_validation()


//Check value as integer

function check_integer ($str, $title, $field_name) {

  $goodchar = " 1234567890";
if(!empty($str)) {
  for ($i=0;$i<strlen($str);$i++) {
    if (strpos($goodchar,$str{$i}) == false) {
      form_set_error($field_name, t('%field_title field should contain only numeric values.',
                                                                       array('%field_title' => $title)));
    }
  }
 }

} //function check_integer()
//Check value as integer with hypan symbol

function check_integer_with_hypan ($str, $title, $field_name) {

  $goodchar = " -1234567890";

  for ($i=0;$i<strlen($str);$i++) {
    if (strpos($goodchar,$str{$i}) == false) {
      form_set_error($field_name, t('%field_title field should contain only numeric values.',
                                                                       array('%field_title' => $title)));
    }
	  if ($str{$i} == '-') {
	  $first_occur=strpos($str, '-');
	  $multi_occur=strpos($str,'-',$first_occur+1);
	  if(!empty($multi_occur))
      form_set_error($field_name, t('%field_title field should contain only numeric values with one hypan(-).',
                                                                       array('%field_title' => $title)));
    }
  }

} //function check_integer_with_hypan()


function check_char_integer($str, $title, $field_name){
$goodchar = "1234567890"; $flag=0;
 for ($i=0;$i<strlen($str);$i++) {
    if (strpos($goodchar,$str{$i}) == true) {
		$flag = 1; break;
    }
  }
  if ($flag != 1) {
  	form_set_error($field_name, t('%field_title field should contain atleast one numeric values.',
                                                                       array('%field_title' => $title)));
  }

}

// Check value as only string

function check_char ($str, $title) {

  $goodchar = " abcdefghijklmnopqrstuvwxyz";

  for ($i=0;$i<strlen($str);$i++) {
    if (!($str{$i} == " ")) {
      if (strpos($goodchar,strtolower($str{$i})) == false) {
	form_set_error('title_length', $title . ' field should contain only alphabetic values.');
        return 0;
      }
    }
  }

} //function check_char()

function years($str, $title, $field_name){

$current_value = $str;

//print "<pre>"; print_r($str); print "</print>";
$current_year = date('Y');

$myear = "1640";
if(!empty($current_value)){
	if ($current_value >= $myear && $current_value <= $current_year ) { }
	else{	form_set_error($field_name, t('Year Range Shoud be 1640 - %field_title.',array('%field_title' => $current_year)));
		//form_set_error($field_name, t('%field_title field should contain only numeric values with one hypan(-).',                                                                      array('%field_title' => $title)));
	}
}


} // function year
function chkcharpincode($str,$title, $field_name) {
    $len = strlen($str);
	if(!empty($str)) {
	if($len < 6 ){
	form_set_error($title, t('%field_title Number Must Have 6 Numbers Only .For Ex(XXXXXX)',array('%field_title' => $title)));}
	}
 }

function startpincode($str,$title,$state, $field_name){
 if(!empty($str)){
     if($state == 'TamilNadu'){
        $str_no = substr($str,0,2);
	if(substr($str,0,2) != '60' && substr($str,0,2) != '61' && substr($str,0,2) != '62' && substr($str,0,2) != '63' && substr($str,0,2) != '64' ){
	form_set_error($title, t('%state %field_title Number Should Not Start With %pin .For Ex(600001)',
                        array('%field_title' => $title,'%pin' =>$str_no,'%state'=>$state)));
	}
     }
     if($state == 'Delhi'){
        $str_no = substr($str,0,2);
	if(substr($str,0,2) != '11' ){
	form_set_error($title, t('%state %field_title Number Should Not Start With %pin .For Ex(110001)',
                        array('%field_title' => $title,'%pin' =>$str_no,'%state'=>$state)));
	}
     }
     if($state == 'Andhra Pradesh'){
        $str_no = substr($str,0,2);
	if(substr($str,0,2) != '50' && substr($str,0,2) != '51' && substr($str,0,2) != '52' && substr($str,0,2) != '53' ){
	form_set_error($title, t('%state %field_title Number Should Not Start With %pin .For Ex(500004)',
                        array('%field_title' => $title,'%pin' =>$str_no,'%state'=>$state)));
	}
     }
     if($state == 'Karnataka'){
        $str_no = substr($str,0,2);
	if(substr($str,0,2) != '56' && substr($str,0,2) != '57' && substr($str,0,2) != '58' && substr($str,0,2) != '59' ){
	form_set_error($title, t('%state %field_title Number Should Not Start With %pin .For Ex(560001)',
                        array('%field_title' => $title,'%pin' =>$str_no,'%state'=>$state)));
	}
     }
     if($state == 'Kerala'){
        $str_no = substr($str,0,2);
	if(substr($str,0,2) != '67' && substr($str,0,2) != '68' && substr($str,0,2) != '69'){
	form_set_error($title, t('%state %field_title Number Should Not Start With %pin .For Ex(670001)',
                        array('%field_title' => $title,'%pin' =>$str_no,'%state'=>$state)));
	}
     }
     if($state == 'Pudcherry'){
        $str_no = substr($str,0,2);
	if(substr($str,0,2) != '60' && substr($str,0,2) != '53' && substr($str,0,2) != '67'){
	form_set_error($title, t('%state %field_title Number Should Not Start With %pin .For Ex(605001)',
                        array('%field_title' => $title,'%pin' =>$str_no,'%state'=>$state)));
	}
     }

}
}
function docu_year($str,$title,$field_name){
	$fyear = substr($str,0,4);
	$secyear = substr($str,5,9);
	$var = "1";
	$current_year = date('Y')+1;
	$doc_year = $fyear + $var;

	if($fyear >=1999 && $secyear <= $current_year && $fyear <= $current_year){
		if($doc_year != $secyear)
		{
			form_set_error($title, t('Year Shoud be %year - %field_title.',array('%field_title' => $doc_year,'%year' => $fyear)));
		}
	}
	else{
			form_set_error($title, t('Year Range Shoud be 1999 - %field_title.',array('%field_title' => $current_year)));
	}

}

function isValidEmail($email,$title,$field_name){

     if(!empty($email) )  {
	$pattern = "^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$";

		if (!eregi($pattern, $email)){
			form_set_error($title, t('Your %field_title is Invaild Format.',array('%field_title' => $title)));
		}

		$badch = array('SELECT','INSERT','DELETE','DROP','ALTER','CHANGE','MODIFY');
	 foreach($badch as $key=>$val) {
		if (preg_match("/$val/i", $email)) {
     	form_set_error($title, t('Your %field_title is Invaild Format.',array('%field_title' => $title)));
		}
	}

    //form_set_error($title, t('Year Email is Invaild Format'));
	//$result = FALSE;
  }

}


function startcode($str,$title, $field_name){
	$len = strlen($str);
	if(!empty($str)){
	if(substr($str,0,1)!= "0"){ form_set_error($title, t('%field_title STD Code Start with 0',array('%field_title' => $title))); }
	}

}
function mobilecode($str,$title, $field_name){
	$len = strlen($str);
	if(!empty($str)){
	if( (substr($str,0,1) == "0") || (substr($str,0,1)== "9") || (substr($str,0,1)== "8") || (substr($str,0,1)== "7") ) { }
	 else {form_set_error($title, t('%field_title Start With 0 or 9 or 8 .For Ex(0XXXXXXXXXX) or Ex(9XXXXXXXXX)',array('%field_title' => $title))); 	}
	}
}
function codenumber($str,$title, $field_name){
 $len = strlen($str);
	if(!empty($str)) {
	if($len >= 3 && $len < 6 ){}else {form_set_error($title, t('%field_title STD Code Number Must Have 3-5 Numbers Only Code.For Ex(XXXXX)',array('%field_title' => $title)));}
	}

}


// Reference URL Validation

function url_validation1($url) {
  // Reference url validation

    $reference_url = $url['und'][0]['value']['#value'];
    $reference_url = url_validation($reference_url);
    $url[0]['value']['#value'] = $reference_url;
    $form_state['values']['field_src_website'][0]['value'] = $reference_url;

    if(!isURL($reference_url) && $reference_url != "") {
      form_set_error('field_src_website', 'Not a valid URL given in reference_url field');
    }
}


// Title Duplication

function duplicate_title($title, $department_id, $form_name) {

  //$qry = "SELECT a.title FROM {node} AS a, {content_type_" . $form_name . "} AS b WHERE a.type = '" . $form_name . "' AND field_src_dept_value = " . $department_id

} // duplicate_title()


// File Upload Validation

function file_upload_validation($field_obj, $file_allowed_obj, $field_name) {

  //$max_file_size = $field_obj[0]['#upload_validators']['filefield_validate_size'][0];
  //$file_size = $field_obj[0]['#value']['filesize'];
  //$file_name = $field_obj[0]['#value']['filename'];
  //s$file_name = $field_obj[0]['#post']['files']['fieldname'];
  $title = $field_obj['#title'];
 /* $allowed_file_type = strtoupper($file_allowed_obj['value']['#value']);*/

 //$allowed_file_type = $field_obj[0]['#upload_validators']['filefield_validate_extensions'][0];
 $file_types = explode(" ", $allowed_file_type);

 /* if ($allowed_file_type == 'PLEASE SELECT FILE TYPE') {
    form_set_error($file_allowed_obj['#name'], t('%field is required', array('%field' => $file_allowed_obj['#title'])));
    return 0;
  }
  if ($allowed_file_type == 'JPG') {
    $allowed_file_type .= " " . 'JPEG';
  }*/
  //$file_types = explode(" ", $allowed_file_type);

  if ($file_name == "") {
    form_set_error($field_obj[0]['upload']['#name'],
                   t('%field field is required, allowed extensions: %types', array('%types' => implode(", ", $file_types),
                                                                                   '%field' => $field_obj['#title'])));
    return 0;
  }

  if ($file_size > $max_file_size) {
    form_set_error($field_name, t('%name field file exceeds 2MB', array('%name' => $title)));
  }


  /*$file_extension = substr(strrchr($file_name, "."), 1);
  if (!in_array(strtoupper($file_extension), $file_types)) {
    form_set_error($field_name, t('Specified file types only allowed to upload: %types', array('%types' => implode(", ", $file_types))));
  }*/
}


// File Upload Validation only images

function file_upload_validation_img($field_obj, $file_allowed_obj, $field_name) {

  //$max_file_size = $field_obj[0]['#upload_validators']['filefield_validate_size'][0];
  //$file_size = $field_obj[0]['#value']['filesize'];
  //$file_name = $field_obj[0]['#value']['filename'];
  //s$file_name = $field_obj[0]['#post']['files']['fieldname'];
  $title = $field_obj['#title'];
 /* $allowed_file_type = strtoupper($file_allowed_obj['value']['#value']);*/

 //$allowed_file_type = $field_obj[0]['#upload_validators']['filefield_validate_extensions'][0];
 $file_types = explode(" ", $allowed_file_type);

  if ($allowed_file_type == 'PLEASE SELECT FILE TYPE') {
    form_set_error($file_allowed_obj['#name'], t('%field is required', array('%field' => $file_allowed_obj['#title'])));
    return 0;
  }
  if ($allowed_file_type == 'JPG') {
    $allowed_file_type .= " " . 'JPEG';
  }
  //$file_types = explode(" ", $allowed_file_type);

  if ($file_name == "") {
    form_set_error($field_obj[0]['upload']['#name'],
                   t('%field field is required, allowed extensions: %types', array('%types' => implode(", ", $file_types),
                                                                                   '%field' => $field_obj['#title'])));
    return 0;
  }

  if ($file_size > $max_file_size) {
    form_set_error($field_name, t('%name field file exceeds 2MB', array('%name' => $title)));
  }


  /*$file_extension = substr(strrchr($file_name, "."), 1);
  if (!in_array(strtoupper($file_extension), $file_types)) {
    form_set_error($field_name, t('Specified file types only allowed to upload: %types', array('%types' => implode(", ", $file_types))));
  }*/
}


// File Upload Validation

function file_upload_validation_D7($file_name, $field_name) {

	//echo "Field : ".$field_name;
	//echo "File : ".$file_name;
    if(empty($file_name)){
	//form_set_error($field_name, t('Kindly choose the upload file.'));
    form_set_error($field_name, t('Kindly choose the upload file '.$field_name.' field', array( $field_name => $title)));
	}

}
  function check_reference_url($url, $title, $field_name, $required) {

	$url = trim($url);
    if ($url == '') {
      if ($required == 1) {
        return 0;
      }
      elseif ($required == 0) {
        form_set_error($field_name, t('%field_name field is required', array('%field_name' => $title)));
      }
    }

    $reference_url = url_validation($url);
    $reference_url = $url;

    if (!valid_url($reference_url)) {
      form_set_error($field_name, t('Not a valid URL given in %field_name field', array('%field_name' => $title)));
    }
	/*elseif ($reference_url =='') {
      form_set_error($field_name, t('Not a valid URL given in %field_name field', array('%field_name' => $title)));
    }*/
    else {

      //url_exists($reference_url, $title, $field_name);
    }
  }

function url_exists($url, $title, $field_name) {

		$agent = "Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)";
		$ch=curl_init();
		curl_setopt ($ch, CURLOPT_URL,$url );
		curl_setopt($ch, CURLOPT_USERAGENT, $agent);
		curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt ($ch,CURLOPT_VERBOSE,false);
		curl_setopt($ch, CURLOPT_TIMEOUT, 5);
		if (curl_exec($ch) === false) {
				$errors = curl_error($ch);
				$explode_errors = explode (" '", $errors);
				form_set_error($field_name, t(' %error, which given in %field_name field', array('%error' => $explode_errors[0] ,
				'%field_name' => $title)));
		}
		curl_close($ch);

}

function check_date_expire($field_object,$field_name) {
    $valid_date = $field_object;

	if ($valid_date != "" && date_validation($valid_date) > 0) {
      form_set_error($field_name, t('Given date in %field_name should not be Greater than today Date',
                                                         array('%field_name' => $field_name)));
      return 1;
    }
    return 0;
  }

  function check_scheduler_date_expire($field_object, $field_name) {
  	$valid_date = $field_object;
	//echo date_validation($valid_date);
    if ($valid_date != "" && date_validation($valid_date) > 0 ) {
      form_set_error($field_name, t('Given date in %field_name should be Greater than today Date',
                                                         array('%field_name' => 'Valid Upto')));
      return 1;
    }
    return 0;
  }

  function Commencement_date($field_object,$title,$field_name) {
  	$valid_date = $field_object;
	//echo "sss".($valid_date);
    if ($valid_date != "" && date_validation($valid_date) <	 0 ) {
      form_set_error($field_name, t('%field_name should be Greater than today Date',
                                                         array('%field_name' => $title)));
      return 1;
    }
    return 0;
  }


  function check_title_duplication($field_object, $form_type, $dept_field_object, $field_name, $nid) {

    $dept_value = $dept_field_object['#value']['value'];
    $title = strtoupper(trim($field_object['#value']));
    $list_nid = array();
    $flag = 0;
	if($form_type != 'profile')  {

		$qry = "SELECT a.title, a.nid FROM {node} AS a, content_type_%s as b
               WHERE a.type = '%s' AND a.nid = b.nid AND b.%s_value = '%d' AND a.nid != '%d'";
    	$qry_result = db_query($qry, $form_type, $form_type, $field_name, $dept_value, $nid);

	}
	else{
    	$qry = "SELECT a.title, a.nid FROM {node} AS a, content_%s as b WHERE a.type = '%s' AND a.nid = b.nid
				AND b.%s_value = '%d' AND a.nid != '%d' ";
		$qry_result = db_query($qry,$field_name,$form_type,$field_name,$dept_value, $nid);
    }
    while ($links = db_fetch_object($qry_result)) {
		//print "<pre>";	print_r($links); print "</pre>";

      if (remove_spaces($title) == remove_spaces($links->title)) {
        $list_nid[] = l($links->nid, 'node/' . $links->nid, array("attributes" =>  array( "target" => "_blank" )));
        $flag = 1;
      }
    }
    if ($flag == 1) {
      $nodes = implode(", ", $list_nid);
      form_set_error($field_object['#name'], t('Following title %title already have been exist ',
                                                    array('%title' => $field_object['#value'])));
   }
  } // function check_title_duplication()



  function remove_spaces($str) {
    $new_str = array();
    $str = strtoupper(trim($str));

    $explode_str = explode(' ', $str);
    for($i = 0; $i< count($explode_str); $i++) {
      if (trim($explode_str[$i]) != '') {
        $new_str[] = $explode_str[$i];
      }
    }
    return implode(' ', $new_str);
  } // function remove_spaces()

  function greg_alter( $m, $d, $y )
	 	                {
	 	                $y = $m == 1 || $m == 2 ? --$y : $y;
	 	                $m = $m == 1 || $m == 2 ? $m + 12 : $m;
	 	                $a = intval( $y / 100 );
	 	                $b = intval( $a / 4 );
	 	                $c = 2 - $a + $b;
	 	                $e = intval( 365.25 * ( $y + 4716 ) );
	 	                $f = intval( 30.6001 * ( $m + 1 ) );
	 	                return $c + $d + $e + $f - 1524.5 + 0.5;
	 	                }



  function check_go_title_duplication($field_object, $form_type, $dept_field_object,$field_name,$date_field_object,$field_name1,$nid) {
  	global $language;

    $dept_value = $dept_field_object['#value']['value'];
    $title = strtoupper(trim($field_object['#value']));

	$field_go_date_value = $date_field_object[0]['value']['date']['#value'];
	list($month, $day, $year) = split('[/.-]', $field_go_date_value);
    $year = "$year";


    $list_nid = array();
    $flag = 0;

    $qry = "SELECT a.title, a.nid,a.vid,b.field_go_date_value,to_char(cast(b.field_go_date_value as date),'YYYY') AS year FROM {node} AS a, content_type_%s as b
           WHERE a.type = '%s' AND a.nid = b.nid AND (a.language='".$language->language."' or a.language = '') AND a.status = '1' AND a.vid = b.vid AND b.%s_value = '%d' AND a.nid != '%d'";
    $qry_result = db_query($qry, $form_type, $form_type, $field_name, $dept_value,$nid);
    // db_query($qry, $form_type, $form_type, $field_name, $dept_value, $nid);


    while ($links = db_fetch_object($qry_result)) {
		//print "<pre>";print_r($links); print "</pre>"; die;
		$date = $links->year;
      if (remove_spaces($title) == remove_spaces($links->title) && $year == $links->year ) {
        $list_nid[] = l($links->nid, 'node/' . $links->nid, array("attributes" =>  array( "target" => "_blank" )));
        $flag = 1;
      }
    }
    if ($flag == 1) {
      $nodes = implode(", ", $list_nid);
      form_set_error($field_object['#name'], t('Following title %title already have been exist',
                                                    array('%title' => $field_object['#value'])));
   }
  }

  function chk_UN_EMAIL($user_name,$e_mail){

   if(!empty($user_name)){

    $query = "select name from {users} WHERE name ='".$user_name."'";

       $result = db_query ($query);
     	$num = pg_num_rows($result);

       if($num !=0){

          form_set_error('name', t('%title is already exists. Please provide another %title', array('%title' => 'User Name')));
       }
   }
   if(!empty($e_mail)){
       $query = "select name from {users} WHERE mail ='".$e_mail."'";

       $result = db_query ($query);
       $num = pg_num_rows($result);

       if($num !=0){
            form_set_error('mail', t('Given %title is already exists. Please provide another %title', array('%title' => 'Email Id')));
   		}
	}
}
//To check Concerned department value
 function chk_concerned_dept($field_object){
     global $user;

	  echo $field_object;
 $profile =  profile2_load_by_user($user, 'main');
 $dept_value = $field_object['#value']['value'];
 	if($dept_value != $user->profile_chekdept && !empty($user->profile_chekdept)){

    	form_set_error('field_act_dpt', t('Please select %dept_name in %field_title field.',
                                                array('%field_title' => $field_object['#title'], '%dept_name' =>dept_namebyvalue($user->profile_chekdept))));
	}
 }

//To get Department Name by Department Value
 function dept_namebyvalue($dept_value){
 	$dept_name_query = db_fetch_object(db_query('SELECT dept_name from depart_mst where dep_id = %d LIMIT 1', $dept_value));
 	return empty($dept_name_query) ? NULL : $dept_name_query->dept_name;
 }

 //to check unique sessions
 /*if(empty($_SESSION['sess_flag']))
     check_session();
  else
unset($_SESSION['sess_flag'])*/

function check_session(){

        /* $query = db_query("SELECT uid from sessions where session like '%%".$_SERVER['REMOTE_ADDR']."%' AND session like '%%".$_SERVER['HTTP_USER_AGENT']."%'");
                               $num = pg_num_rows($query);
                               if($num == '1'){
                                $query = db_query("SELECT uid from sessions where session like '%%".$_SERVER['REMOTE_ADDR']."%' AND session like '%%".$_SERVER['HTTP_USER_AGENT']."%'");
                               }
                                 $num = pg_num_rows($query);
                                if($num > 1){


                                while($result =  db_fetch_array($query)){

                                    // echo "UPDATE SET uid = 0 WHERE uid =".$result['uid'];
//                                     $query = db_query("UPDATE SET uid = 0 WHERE uid =".$result['uid']);
                                     $query = db_query("DELETE FROM sessions where uid =".$result['uid']);

                                     drupal_goto('logout');
                                }
                                }*/
 $ses_id = session_id();
 if(!empty($ses_id) && empty($_SESSION[session_id().'UA'])){
$_SESSION[session_id().'UA'] = $_SERVER['HTTP_USER_AGENT'];
$_SESSION[session_id().'RA'] = $_SERVER['REMOTE_ADDR'];
 }

if(!empty($_SESSION[session_id().'UA'] ) || !empty($_SESSION[session_id().'RA'])){

    if(($_SESSION[session_id().'UA'] != $_SERVER['HTTP_USER_AGENT'])|| ($_SESSION[session_id().'RA'] != $_SERVER['REMOTE_ADDR'])){
      session_destroy();
    drupal_goto('invalid');

    }

}

}
?>
